import { useControlController, useNamespace } from '@ibiz-template/vue3-util';
import { defineComponent, PropType, VNode } from 'vue';
import { IDEDRBar } from '@ibiz/model-core';
import { useRouter } from 'vue-router';
import { IDRBarItemsState } from '@ibiz-template/runtime';
import { DRBarController } from './drbar.controller';

export const DRBarControl = defineComponent({
  name: 'IBizDrBarControl',
  props: {
    modelData: { type: Object as PropType<IDEDRBar>, required: true },
    context: { type: Object as PropType<IContext>, required: true },
    params: { type: Object as PropType<IParams>, default: () => ({}) },
  },
  setup() {
    const c = useControlController((...args) => new DRBarController(...args));
    const ns = useNamespace(`control-${c.model.controlType!.toLowerCase()}`);
    const router = useRouter();

    c.setRouter(router);
    const handleSelect = (key: string): void => {
      c.handleSelectChange(key);
    };

    const renderMenuItems = (item: IDRBarItemsState): VNode | undefined => {
      if (!item.hidden) {
        if (item.children) {
          return (
            <el-sub-menu class={ns.b('group')} index={item.tag}>
              {{
                default: () =>
                  item.children!.map(child => {
                    return renderMenuItems(child);
                  }),
                title: () => [
                  <iBizIcon
                    class={ns.e('icon')}
                    icon={item.sysImage}
                  ></iBizIcon>,
                  <span>{item.caption}</span>,
                ],
              }}
            </el-sub-menu>
          );
        }
        return (
          <el-menu-item
            class={ns.e('item')}
            index={item.tag}
            disabled={item.disabled}
          >
            <iBizIcon class={ns.e('icon')} icon={item.sysImage}></iBizIcon>
            <span>{item.caption}</span>
          </el-menu-item>
        );
      }
    };

    return {
      c,
      ns,
      handleSelect,
      renderMenuItems,
    };
  },
  render() {
    const { isCreated, drBarItems } = this.c.state;
    return (
      <iBizControlBase controller={this.c} class={this.ns.b()}>
        {isCreated && (
          <el-menu
            default-active={drBarItems[0]?.tag}
            onSelect={this.handleSelect}
          >
            {drBarItems.map(item => {
              return this.renderMenuItems(item);
            })}
          </el-menu>
        )}
      </iBizControlBase>
    );
  },
});
